package com.core.action;

import java.util.concurrent.ScheduledFuture;

import org.apache.log4j.Logger;

/**
 * 冒牌计时器
 * 定时被执行的action,可指定执行次数
 * @author King
 * 
 */
public abstract class TimeAction extends BaseAction
{
	private static final Logger log = Logger.getLogger(TimeAction.class);
	/** 间隔触发的毫秒数 */
	protected long intervalMill;

	/** 执行次数,负数为无限次执行 */
	private int count = -1;

	/** 是否定时结束 */
	private boolean isOver = false;

	private ScheduledFuture<?> future;
	
	
	/**下次执行时间**/
	private long nextExecuteTime;

	/**
	 * 无限次定时
	 * 
	 * @param intervalMill
	 *            时间间隔	
	 */
	public TimeAction(long intervalMill) {
		this.intervalMill = intervalMill;
		// 设定执行次数
		this.count = -1;
	}

	/**
	 * 限制次数类型定时
	 * 
	 * @param intervalMill
	 *            时间间隔
	 * @param count
	 *            次数
	 */
	public TimeAction(long intervalMill, int count) {
		this.intervalMill = intervalMill;
		// 设定执行次数
		this.count = count>0?count:1;
	}

	public void setFutrue(ScheduledFuture<?> future) {
		this.future = future;
	}
	
	

	/**
	 * 获取时间间隔
	 * 
	 * @return
	 */
	public long getIntervalMill() {
		return this.intervalMill;
	}

	@Override
	public void execute() throws Exception {
		if(count!=-1)
		{
			count--;
			if (count < 1)
				over();
		}
		long start = System.nanoTime();
		executeOnTime();
		nextExecuteTime = start+intervalMill;
		double userTime = (System.nanoTime() - start)/1000.0/1000.0;
		if(userTime>10)
		{
			log.error(getClass().getName()+" 执行时间 :"+userTime);
		}
	}
	
	public boolean canExecute(long now)
	{
		if(now<nextExecuteTime)
			return false;
		return true;
	}
	
	protected long getCurTime()
	{
		return System.currentTimeMillis();
	}
	

	public abstract void executeOnTime() throws Exception;

	
	public boolean isOver() {
		return isOver;
	}

	public void over() {
		if(future!=null)
			future.cancel(false);
		this.isOver = true;
	}

}
